<template>
  <div class="tradeWrap">
    <div class="tabTitle">
      <span :class="{active: orderType === 1}" @click="toggleOrderType(1)">{{lang['check price']}}</span>
      <span :class="{active: orderType === 0}" @click="toggleOrderType(0)">{{lang['market price']}}</span>
    </div>

    <div class="tradeBox buy">

      <div class="head">
        <em class="desc">{{lang['buy for a rise']}} {{pair.SellerCoinCode}}</em>
        <span class="available">
          {{lang['available']}} {{pair.BuyerCoinCode}}：
          <em>{{buyerAsset.AvailableAmount | fixDecimal | currency('USD', '', pair.buyerPrecision) | fillDecimal(pair.buyerPrecision)}}</em>
        </span>
      </div>

      <div class="inputBox price" :class="{error: buyParams.priceError === true, disabled: orderType === 0}">
        <label class="label" for="tradingBuyPriceInput">{{lang['price']}}</label>
        <input class="input" type="text"
          :placeholder="lang['please enter price']"
          ref="buyPrice"
          v-model="buyParams.price"
          :data-fee="tradeStrategy[pair.TradingConfigID] && feeRate"
          :data-min="pair && pair.MinBuyQuantity"
          data-id="tradingBuyPriceInput"
          @focus="setCalcWhich($event, buyParams, 'price')"
          @input="buyParams.priceError = false, buyParams.quantityRate = 0">
        <span class="desc" v-text="pair.BuyerCoinCode"></span>
        <p class="set">
          <i class="up" @click="modifyPrice('+', buyParams)">+</i>
          <i class="down" @click="modifyPrice('-', buyParams)">-</i>
        </p>
      </div>

      <div class="inputBox amount" v-show="orderType === 1" :class="{error: buyParams.quantityError === true}">
        <label class="label" for="tradingBuyQuantityInput">{{lang['quantity']}}</label>
        <input class="input" type="text"
          :placeholder="lang['please enter quantity']"
          ref="buyQuantity"
          v-model="buyParams.quantity"
          data-id="tradingBuyQuantityInput"
          @focus="setCalcWhich($event, buyParams, 'quantity')"
          @input="buyParams.quantityError = false, buyParams.quantityRate = 0">
        <span class="desc" v-text="pair.SellerCoinCode"></span>
      </div>
      <!-- 市价数量输入框 -->
      <div class="inputBox amount" v-show="orderType === 0" :class="{error: buyParams.quantityError === true}">
        <label class="label" for="marketBuyQuantityInput">{{lang['quantity']}}</label>
        <input class="input" type="text"
          :placeholder="lang['please enter quantity']"
          ref="marketBuyQuantity"
          v-model="buyParams.quantity"
          data-id="marketBuyQuantityInput"
          @input="buyParams.quantityError = false, buyParams.quantityRate = 0">
        <span class="desc" v-text="pair.SellerCoinCode"></span>
      </div>

      <div class="inputBox amount" :class="{disabled: orderType === 0}">
        <label class="label" for="tradingBuyTotalInput">{{lang['trading notional']}}</label>
        <input class="input" type="text"
          ref="buyTotal"
          v-model="buyParams.total"
          :placeholder="lang['please enter the amount']"
          data-id="tradingBuyTotalInput"
          @focus="setCalcWhich($event, buyParams, 'total')">
        <span class="desc" v-text="pair.BuyerCoinCode"></span>
      </div>

      <!--div class="quantityRates">
        <span class="item" :class="{active: buyParams.quantityRate === 0.25}" @click="modifyBuyQuantityByRate(buyParams, 0.25)">25%</span>
        <span class="item" :class="{active: buyParams.quantityRate === 0.50}" @click="modifyBuyQuantityByRate(buyParams, 0.50)">50%</span>
        <span class="item" :class="{active: buyParams.quantityRate === 0.75}" @click="modifyBuyQuantityByRate(buyParams, 0.75)">75%</span>
        <span class="item" :class="{active: buyParams.quantityRate === 1}" @click="modifyBuyQuantityByRate(buyParams, 1)">100%</span>
      </div>

      <p class="total" v-show="orderType === 1">
        {{lang['amount of money']}}：
        <em>
          {{buyParams.total | currency('USD', '', pair.buyerPrecision) | fillDecimal(pair.buyerPrecision)}}
          {{pair.BuyerCoinCode}}
        </em>
      </p-->

      <button class="btn buy" @click="sendOrder(0)">{{lang['buy for a rise'].toUpperCase() + ' ' + (pair.SellerCoinCode !== undefined ? pair.SellerCoinCode : '')}}</button>
    </div>


    <div class="tradeBox sell">

      <div class="head">
        <em class="desc">{{lang['offtake']}} {{pair.SellerCoinCode}}</em>
        <span class="available">
          {{lang['available']}} {{pair.SellerCoinCode}}：
          <em>{{sellerAsset.AvailableAmount | fixDecimal | currency('USD', '', pair.sellerPrecision) | fillDecimal(pair.sellerPrecision)}}</em>
        </span>
      </div>

      <div class="inputBox price" :class="{error: sellParams.priceError === true, disabled: orderType === 0}">
        <label class="label" for="tradingSellPriceInput">{{lang['price']}}</label>
        <input class="input" type="text"
          :placeholder="lang['please enter price']"
          ref="sellPrice"
          v-model="sellParams.price"
          :data-min="pair && pair.MinSellQuantity"
          data-id="tradingSellPriceInput"
          @input="sellParams.priceError = false"
          @focus="setCalcWhich($event, sellParams, 'price')">
        <span class="desc" v-text="pair.BuyerCoinCode"></span>
        <p class="set">
          <i class="up" @click="modifyPrice('+', sellParams)">+</i>
          <i class="down" @click="modifyPrice('-', sellParams)">-</i>
        </p>
      </div>

      <div class="inputBox amount" v-show="orderType === 1" :class="{error: sellParams.quantityError === true}">
        <label class="label" for="tradingSellQuantitynput">{{lang['quantity']}}</label>
        <input class="input" type="text"
          :placeholder="lang['please enter quantity']"
          ref="sellQuantity"
          v-model="sellParams.quantity"
          @input="sellParams.quantityError = false, sellParams.quantityRate = 0"
          data-id="tradingSellQuantitynput"
          @focus="setCalcWhich($event, sellParams, 'quantity')">
        <span class="desc" v-text="pair.SellerCoinCode"></span>
      </div>
      <!-- 市价数量输入框 -->
      <div class="inputBox amount" v-show="orderType === 0" :class="{error: sellParams.quantityError === true}">
        <label class="label" for="marketSellQuantityInput">{{lang['quantity']}}</label>
        <input class="input" type="text"
          :placeholder="lang['please enter quantity']"
          ref="marketSellQuantity"
          v-model="sellParams.quantity"
          data-id="marketSellQuantityInput"
          @input="sellParams.quantityError = false, sellParams.quantityRate = 0">
        <span class="desc" v-text="pair.SellerCoinCode"></span>
      </div>

      <div class="inputBox amount" :class="{disabled: orderType === 0}">
        <label class="label" for="tradingSellTotalInput">{{lang['trading notional']}}</label>
        <input class="input" type="text"
          ref="sellTotal"
          v-model="sellParams.total"
          :placeholder="lang['please enter the amount']"
          data-id="tradingSellTotalInput"
          @focus="setCalcWhich($event, sellParams, 'total')">
        <span class="desc" v-text="pair.BuyerCoinCode"></span>
      </div>

      <!--div class="quantityRates">
        <span class="item" :class="{active: sellParams.quantityRate === 0.25}" @click="modifySellQuantityByRate(sellParams, 0.25)">25%</span>
        <span class="item" :class="{active: sellParams.quantityRate === 0.50}" @click="modifySellQuantityByRate(sellParams, 0.50)">50%</span>
        <span class="item" :class="{active: sellParams.quantityRate === 0.75}" @click="modifySellQuantityByRate(sellParams, 0.75)">75%</span>
        <span class="item" :class="{active: sellParams.quantityRate === 1}" @click="modifySellQuantityByRate(sellParams, 1)">100%</span>
      </div>

      <p class="total" v-show="orderType === 1">
        {{lang['amount of money']}}：
        <em>
          {{sellParams.total | currency('USD', '', pair.buyerPrecision) | fillDecimal(pair.buyerPrecision)}}
          {{pair.BuyerCoinCode}}
        </em>
      </p-->

      <button class="btn sell" @click="sendOrder(1)">{{lang['offtake'].toUpperCase() + ' ' + (pair.SellerCoinCode !== undefined ? pair.SellerCoinCode : '')}}</button>
    </div>

    <div v-show="!userInfo.userName" class="loginShade">
      <p class="login">
        <router-link :to="{path: '/user/login', query: {from: $route.name}}">{{lang.headerLogin}}</router-link>
        <i class="line"></i>
      </p>
      <p class="register">
        <router-link :to="{path: '/user/register', query: {from: $route.name}}" class="a2">{{lang.headerRegistration}}</router-link>
      </p>
    </div>

    <SwModal :isShow.sync="isShowTradePasswordModal" title="" :isShowBg="true" :isShowCloseBtn="true" :noText="''" :okText="lang['determineBth']" :ok="confirmTradePassword" :no="cancelTradePassword">
      <div class="tradePasswordBox">
        <p class="tip">{{lang['pleaseEnterAFundPassword']}}</p>
        <input type="password" v-model="tradePassword" maxlength="6">
        <p class="tip error" v-text="tradePasswordError"></p>
      </div>
    </SwModal>
  </div>
</template>

<script>
import SwModal from '@/components/SwModal'
import ModalApi from '@/components/SwModal/api.js'
import EventBus from '@/service/EventBus.js'
import codeHandles from '@/service/Http/codeHandles.js'
import Decimal from '@/libs/decimal.min.js'
import commonFilter from '@/filters/common.js'
import CheckCurrencyOnInput from '@/utils/CheckCurrencyOnInput.js'
import Utils from '@/utils/Utils.js'
import { mapActions } from 'vuex'

let getDefaultParams = () => ({
  price: '',
  quantity: '',
  total: '',
  quantityRate: 0,
  priceError: false,
  quantityError: false
})

export default {
  props: [
    'userId',
    'userInfo',
    'lang'
  ],
  data () {
    return {
      pair: {},
      // price: '',
      // quantity: '',
      // total: 0,,
      // priceError: false,
      // quantityError: false,
      orderType: 1, // 0、Market   1、Limit
      buyParams: getDefaultParams(),
      sellParams: getDefaultParams(),
      buyParamsTemp: getDefaultParams(),
      sellParamsTemp: getDefaultParams(),
      bestPrices: [],

      assetsList: [],
      isGotPair: false, // 只有pair和assets得到了才能得出buyerAsset
      isGotAssetsList: false,
      buyerAsset: {}, // 可用资产（用于购买）
      sellerAsset: {},

      tradePassword: '',
      isShowTradePasswordModal: false,
      tradePasswordError: '',

      orderSide: '',

      latestPrice: {},
      isFirstGetBestPrices: true,

      isCalcPrice: false,
      isCalcQuantity: false,
      isCalcTotal: false,

      tradeStrategy: [], // 交易策略（包括手续费）
      customer: {},
      KYCRule: {}
    }
  },
  components: {
    SwModal
  },
  watch: {
    'buyParams.price' (nv) {
      // 有时谷歌浏览器，input框不会实时变化，所以这里再次强化修改input值
      this.$refs.buyPrice.value = nv
      this.buyParams.priceError = false// 只要有变化则清除错误提示
    },
    'buyParams.quantity' (nv) {
      this.$refs.buyQuantity.value = nv
      this.buyParams.quantityError = false
    },
    'buyParams.total' (nv) {
      this.$refs.buyTotal.value = nv
    },
    'sellParams.price' (nv) {
      this.$refs.sellPrice.value = nv
      this.sellParams.priceError = false
    },
    'sellParams.quantity' (nv) {
      this.$refs.sellQuantity.value = nv
      this.sellParams.quantityError = false
    },
    'sellParams.total' (nv) {
      this.$refs.sellTotal.value = nv
    }
  },
  computed: {
    // isDisableBuy () {
    //   let isDisable = false
    //   if (this.orderType === 0) {
    //     // 若是市价，最新价*110%*数量大余可用余额 则买入按钮变灰
    //     if (this.latestPrice.price * 1.1 * this.buyParams.quantity > this.buyerAsset.AvailableAmount) {
    //       isDisable = true
    //     }
    //   } else if (this.orderType === 1) {
    //     // 若是限介，则对比原价
    //     if (this.buyParams.total > this.buyerAsset.AvailableAmount) {
    //       isDisable = true
    //     }
    //   }
    //   return isDisable
    // },
    // isDisableSell () {
    //   let isDisable = false
    //   if (this.sellParams.quantity > this.sellerAsset.AvailableAmount) {
    //     isDisable = true
    //   }
    //   return isDisable
    // }
    feeRate () {
      return this.tradeStrategy[this.pair.TradingConfigID] ? this.tradeStrategy[this.pair.TradingConfigID].TriggerFeeRate : 0
    }
  },
  methods: {
    ...mapActions(['defineLangText']),
    toggleOrderType (type) {
      this.orderType = type
      // 市价
      if (this.orderType === 0) {
        this.resetParams()
        this.defineLangText({
          vm: this.buyParams,
          modelKey: 'price',
          langTextKey: 'market price'
        })
        this.buyParams.total = '--'
        this.defineLangText({
          vm: this.sellParams,
          modelKey: 'price',
          langTextKey: 'market price'
        })
        this.sellParams.total = '--'
      } else {
        this.buyParams = this.buyParamsTemp
        this.sellParams = this.sellParamsTemp
      }
    },
    confirmTradePassword () {
      this.tradePasswordError = ''
      this.sendOrder(this.orderSide)
    },
    cancelTradePassword () {
      this.tradePassword = ''
      this.isShowTradePasswordModal = false
    },
    fillIn (key, val, params) { // fillin price or quantity
      let lastValue = params[key]
      params[key] = val
      params[key + 'Error'] = false
      this.setCalcWhich({}, params, key)
      this.calcWhich(params[key], lastValue, {}, params, key)
    },
    sendOrder (orderSide) {
      if (!this.userInfo.userName) {
        codeHandles['51001']()
        return
      }

      // 判断是否需要认证
      if (this.KYCRule.IsEnaled && this.customer.VerifyResult !== 2) {
        let content
        let okText = 'to authenticate'
        if (this.customer.VerifyResult === 0) {
          content = 'c2c sell buy real name authentication'  // '您还没有实名认证，不能交易',
        }
        if (this.customer.VerifyResult === 1) {
          content = 'c2C your real name certification failed' // "您的实名认证未通过，请重新认证"
        }
        if (this.customer.VerifyResult === 3) { // 您的实名认证正在审核中，请耐心等待'
          content = '42075'
          okText = 'determineBth'
        }

        let handle = ModalApi.confirm({
          isShowCloseBtn: true,
          isCloseOnClickBg: true,
          modalClass: 'commonModal smallModal',
          title: 'prompt message',
          content: content,
          noText: '', // '取消',
          okText: okText, // '去认证',
          isShowBg: true,
          ok: () => {
            // 审核中不需要跳去认证
            this.customer.VerifyResult !== 3 && this.$router.push({path: '/safety?isToggleCaidVerified=true'})
            handle.close()
          }
        })
        return
      }

      // 这里的orderSide是其它地方相反的，因为后台参数如此
      let params = orderSide === 1 ? this.sellParams : this.buyParams

      if (!parseFloat(params.price) && this.orderType === 1) {
        params.priceError = true
      }
      if (!parseFloat(params.quantity)) {
        params.quantityError = true
      }
      if (params.priceError || params.quantityError) return

      if (params === this.buyParams && params.quantity < this.pair.MinBuyQuantity) {
        ModalApi.message(this.lang['tradingPage min buy quantity'].replace('{quantity}', this.pair.MinBuyQuantity + ' ' + this.pair.SellerCoinCode))
        return
      }

      if (params === this.sellParams && params.quantity < this.pair.MinSellQuantity) {
        ModalApi.message(this.lang['tradingPage min sell quantity'].replace('{quantity}', this.pair.MinSellQuantity + ' ' + this.pair.SellerCoinCode))
        return
      }

      this.orderSide = orderSide

      this.$http.post('Trade/SendOrder', {
        UserID: this.userId,
        TradingConfigID: this.pair.TradingConfigID,
        Symbol: this.pair.Symbol,
        Quantity: params.quantity,
        Price: params.price,
        Side: this.orderSide,
        Type: this.orderType,
        TradePassword: this.tradePassword
      }, {
        ignorableCodes: '41014, 51025, 51044'
      }).then((res) => {
        if (res.StatusCode === '200') {
          // ModalApi.message('下单成功')
          if (this.orderSide === 0) {
            // this.buyParams = getDefaultParams()
            this.buyParams.quantity = ''
            this.buyParams.total = ''
            this.buyParams.quantityRate = 0
            this.buyParams.priceError = false
            this.buyParams.quantityError = false
            // 市价
            if (this.orderType === 0) {
              this.defineLangText({
                vm: this.buyParams,
                modelKey: 'price',
                langTextKey: 'market price'
              })
              this.buyParams.total = '- -'
            }
            gtag('event', '币币交易', {
              'event_category': '买入',
              'event_label': '买入完成',
              'value': '0'
            })
          } else {
            // this.sellParams = getDefaultParams()
            this.sellParams.quantity = ''
            this.sellParams.total = ''
            this.sellParams.quantityRate = 0
            this.sellParams.priceError = false
            this.sellParams.quantityError = false
            // 市价
            if (this.orderType === 0) {
              this.defineLangText({
                vm: this.sellParams,
                modelKey: 'price',
                langTextKey: 'market price'
              })
              this.sellParams.total = '- -'
            }
            gtag('event', '币币交易', {
              'event_category': '卖出',
              'event_label': '卖出完成',
              'value': '1'
            })
          }
          // this.isFirstGetBestPrices = true
          // EventBus.$emit('buyOrsallComplete', {})

          // 重置密码框参数
          this.isShowTradePasswordModal && (this.isShowTradePasswordModal = false)
          this.tradePassword && (this.tradePassword = '')
        } else if (res.StatusCode === '41014') { // 需要资金密码
          this.isShowTradePasswordModal = true
        } else if (res.StatusCode === '51025') { // 资金密码错误
          this.isShowTradePasswordModal = true
          this.tradePasswordError = this.lang['51025']
        } else if (res.StatusCode === '51044') { // 最小买卖数量
          if (params === this.buyParams) {
            ModalApi.message(this.lang['tradingPage min buy quantity'].replace('{quantity}', this.pair.MinBuyQuantity + ' ' + this.pair.SellerCoinCode))
          } else if (params === this.sellParams) {
            ModalApi.message(this.lang['tradingPage min sell quantity'].replace('{quantity}', this.pair.MinSellQuantity + ' ' + this.pair.SellerCoinCode))
          }
        }
      })
    },
    resetParams () {
      this.buyParamsTemp = this.buyParams
      this.sellParamsTemp = this.sellParams

      this.buyParams = getDefaultParams()
      this.sellParams = getDefaultParams()
    },
    modifyMinValue (value, min, precision, sign) { // 0减 1加= value
      let v = new Decimal(value)
      if (sign === '-') value = v.sub(min).toFixed(precision)
      if (sign === '+') value = v.add(min).toFixed(precision)
      if (value < 0) {
        return false
      }
      return value
    },
    modifyPrice (sign, params) {
      if (!params.price) return
      let value = this.modifyMinValue(params.price, this.pair.MinBuyerCoinPrecision, this.pair.buyerPrecision, sign)
      if (value !== false) {
        let lastValue = params.price
        params.price = value
        this.setCalcWhich({}, params, 'price')
        this.calcWhich(params.price, lastValue, {}, params, 'price')
      }
    },
    // 设置计算price
    setCalcWhich ($event, params, from) {
      // *isCalcPrice、isCalcQuantity和isCalcTotal其中只能有一者为真
      // 思维方式是：
      // 1输入框值为空时为0，不为空时为1
      // 2例子：当聚焦在价格输入框时，把数量和总额输入框当成两个布尔值从00到11考虑各种情况

      this.isCalcPrice = false
      this.isCalcQuantity = false
      this.isCalcTotal = false

      // 当输入价格时：
      // 00当数量为空且总额为空时，啥都不做
      // 01当数量为空且总额不为空时，计算数量
      // 10当数量不为空且总额为空时，计算总额
      // 11当数量不为空且总额不为空时，计算总额
      if (from === 'price') {
        // 01当数量为空且总额不为空时，计算数量
        if (!parseFloat(params.quantity) && parseFloat(params.total)) {
          this.isCalcQuantity = true
        }
        // 10当数量不为空且总额为空时，计算总额
        if (parseFloat(params.quantity) && !parseFloat(params.total)) {
          this.isCalcTotal = true
        }
        // 11当数量不为空且总额不为空时，计算总额
        if (parseFloat(params.quantity) && parseFloat(params.total)) {
          this.isCalcTotal = true
        }
      }

      // 当输入数量时：
      // 00当价格为空且总额为空时，啥都不做
      // 01当价格为空且总额不为空时，计算价格
      // 10当价格不为空且总额为空时，计算总额
      // 11当价格不为空且总额不为空时，计算总额
      if (from === 'quantity') {
        // 01当价格为空且总额不为空时，计算价格
        if (!parseFloat(params.price) && parseFloat(params.total)) {
          this.isCalcPrice = true
        }
        // 10当价格不为空且总额为空时，计算总额
        if (parseFloat(params.price) && !parseFloat(params.total)) {
          this.isCalcTotal = true
        }
        // 11当价格不为空且总额不为空时，计算总额
        if (parseFloat(params.price) && parseFloat(params.total)) {
          this.isCalcTotal = true
        }
      }

      // 当输入总额时：
      // 00当价格为空且数量为空时，啥都不做
      // 01价格为空且数量不为空时，计算价格
      // 10价格不为空且数量为空时，计算数量
      // 11价格不为空且数量不为空时，计算数量
      if (from === 'total') {
        // 01价格为空且数量不为空时，计算价格
        if (!parseFloat(params.price) && parseFloat(params.quantity)) {
          this.isCalcPrice = true
        }
        // 10价格不为空且数量为空时，计算数量
        if (parseFloat(params.price) && !parseFloat(params.quantity)) {
          this.isCalcQuantity = true
        }
        // 11价格不为空且数量不为空时，计算数量
        if (parseFloat(params.price) && parseFloat(params.quantity)) {
          this.isCalcQuantity = true
        }
      }
      // console.log('是否计算价格：', this.isCalcPrice)
      // console.log('是否计算数量：', this.isCalcQuantity)
      // console.log('是否计算总额：', this.isCalcTotal)
    },
    // 计算包含费率的total
    getTotalWithFee (total) {
      total = parseFloat(total) ? total : 0
      total = new Decimal(total)
      return total.mul(1 + this.feeRate).toFixed(10)
    },
    // 计算包含费率的最大total
    getMaxBuyTotalWithFee () {
      // price * (1 + feeRate) * quantity = total => total / (1 + feeRate) = price * quantity
      let availableAmount = new Decimal(this.buyerAsset.AvailableAmount)
      let maxTotal = availableAmount.div(1 + this.feeRate).toFixed(10)
      return maxTotal
    },
    // 计算包含费率的价格
    calcPrice (total, quantity) {
      total = parseFloat(total) ? total : 0
      quantity = parseFloat(quantity) ? quantity : 0
      total = new Decimal(total)
      if (!quantity) return '' // 除数不能为0，不然会无限大
      let price = commonFilter.fillDecimal(total.div(quantity).toFixed(10), this.pair.buyerPrecision)
      return parseFloat(price) ? price : commonFilter.fillDecimal(0, this.pair.buyerPrecision)
    },
    // 计算包含费率的数量
    calcQuantity (total, price) {
      total = parseFloat(total) ? total : 0
      price = parseFloat(price) ? price : 0
      total = new Decimal(total)
      if (!price) return '' // 除数不能为0，不然会无限大
      let quantity = commonFilter.fillDecimal(total.div(price).toFixed(10), this.pair.sellerPrecision)
      // console.log('价格：', price)
      // console.log('数量：', quantity)
      // console.log('总额：', total.toNumber())
      // console.log('js：', total / price)
      return parseFloat(quantity) ? quantity : commonFilter.fillDecimal(0, this.pair.sellerPrecision)
    },
    // 计算包含费率的总额
    calcTotal (price, quantity) {
      price = parseFloat(price) ? price : 0
      quantity = parseFloat(quantity) ? quantity : 0
      price = new Decimal(price)
      let total = commonFilter.fillDecimal(price.mul(quantity).toFixed(10), this.pair.buyerPrecision)
      return parseFloat(total) ? total : commonFilter.fillDecimal(0, this.pair.buyerPrecision)
    },
    // 买时，输入价格，当数量不为空时，价格*数量不能超过余额，超过时压缩价格
    checkBuyTotalOnInputPrice (params, flag) {
      let quantity = parseFloat(params.quantity) ? params.quantity : 0
      let total = parseFloat(params.total) ? params.total : 0
      let totalWithFee = this.getTotalWithFee(total)
      if (parseFloat(totalWithFee) > this.buyerAsset.AvailableAmount) {
        total = this.getMaxBuyTotalWithFee()
        params.price = this.calcPrice(total, quantity)
        // 上面的total是带着后面所有小数进行计算的，但数量会截取小数位，有可能此时价格*数量不等于总额，这里再重新计算下再用价格和数量计算出总额
        params.total = this.calcTotal(params.price, params.quantity)
      }
    },
    // 买时，输入数量，当价格不为空时，价格*数量不能超过余额，超过时压缩数量
    checkBuyTotalOnInputQuantity (params, flag) {
      let price = parseFloat(params.price) ? params.price : 0
      let total = parseFloat(params.total) ? params.total : 0
      let totalWithFee = this.getTotalWithFee(total)
      if (parseFloat(totalWithFee) > this.buyerAsset.AvailableAmount) {
        total = this.getMaxBuyTotalWithFee()
        params.quantity = this.calcQuantity(total, price)
        // 上面的total是带着后面所有小数进行计算的，但数量会截取小数位，有可能此时价格*数量不等于总额，这里再重新计算下再用价格和数量计算出总额
        params.total = this.calcTotal(params.price, params.quantity)
      }
    },
    // 计算价格|数量|总额
    calcWhich (newVal, lastVal, event, params, from) {
      if (newVal === lastVal) return
      // 输入价格时，小数位溢出则不可再输
      // if (from === 'price' && Utils.getDecimals(params.price).length > this.pair.buyerPrecision) {
      //   params.price = event.target.value = commonFilter.limitDecimal(params.price, this.pair.buyerPrecision)
      //   return
      // }
      // 输入数量时
      if (from === 'quantity') {
        // 截取小数位
        // if (Utils.getDecimals(params.quantity).length > this.pair.sellerPrecision) {
        //   return
        //   // params.quantity = event.target.value = commonFilter.limitDecimal(params.quantity, this.pair.sellerPrecision)
        // }
        // 卖出
        if (params === this.sellParams) {
          // 卖时检测数量是否超过余额
          if (parseFloat(params.quantity) > this.sellerAsset.AvailableAmount) {
            params.quantity = commonFilter.fillDecimal(this.sellerAsset.AvailableAmount, this.pair.sellerPrecision)
            event && event.target && (event.target.value = params.quantity) // 从盘口和+-传过来的是没有event的
          }
        }
      }
      // 输入总额时
      if (from === 'total') {
        // 截取小数位
        // if (Utils.getDecimals(params.total).length > this.pair.buyerPrecision) {
        //   params.total = event.target.value = commonFilter.limitDecimal(params.total, this.pair.buyerPrecision)
        // }
        // 买入
        if (params === this.buyParams) {
          let totalWithFee = this.getTotalWithFee(params.total)
          if (parseFloat(totalWithFee) > this.buyerAsset.AvailableAmount) {
            // 买时检测总额是否超过余额
            if (this.isCalcPrice) {
              this.checkBuyTotalOnInputPrice(params)
              return
            }
            if (this.isCalcQuantity) {
              this.checkBuyTotalOnInputQuantity(params)
              return
            }
            params.total = commonFilter.fillDecimal(this.getMaxBuyTotalWithFee(), this.pair.buyerPrecision)
            event && event.target && (event.target.value = params.total)
          }
        }
      }

      // 买入计算
      if (params === this.buyParams) {
        // 计算价格
        if (this.isCalcPrice) {
          params.price = this.calcPrice(params.total, params.quantity)
        }
        // 计算数量
        if (this.isCalcQuantity) {
          params.quantity = this.calcQuantity(params.total, params.price)
          if (from === 'total') {
            this.checkBuyTotalOnInputQuantity(params)
          }
        }
        // 计算总额
        if (this.isCalcTotal) {
          params.total = this.calcTotal(params.price, params.quantity)
          if (from === 'price') {
            this.checkBuyTotalOnInputPrice(params)
          }
          if (from === 'quantity') {
            this.checkBuyTotalOnInputQuantity(params)
          }
        }
      }

      // 卖出计算
      if (params === this.sellParams) {
        // 计算价格
        if (this.isCalcPrice) {
          params.price = this.calcPrice(params.total, params.quantity)
        }
        // 计算数量
        if (this.isCalcQuantity) {
          let timeout = from === 'price' ? 1000 : 0
          clearTimeout(this.calcQuantityTimer)
          this.calcQuantityTimer = setTimeout(() => {
            params.quantity = this.calcQuantity(params.total, params.price)
            if (from === 'price') {
              this.checkSellQuantityOnInputPrice(params)
            }
            if (from === 'total') {
              this.checkSellQuantityOnInputTotal(params)
            }
          }, timeout)
        }
        // 计算总额
        if (this.isCalcTotal) {
          params.total = this.calcTotal(params.price, params.quantity)
        }
      }
    },
    // 卖时，输入总额，当价格不为空时，总额/价格不能超过最大可卖数量，超过时数量等于最大可卖数量，再用总额=价格*数量
    checkSellQuantityOnInputTotal (params) {
      let maxQuantity = commonFilter.fillDecimal(this.sellerAsset.AvailableAmount, this.pair.sellerPrecision)
      if (parseFloat(params.quantity) >= parseFloat(commonFilter.fillDecimal(this.sellerAsset.AvailableAmount, this.pair.sellerPrecision))) {
        params.quantity = maxQuantity
        params.total = this.calcTotal(params.price, params.quantity)
      }
    },
    // 卖时，输入总额，当价格不为空时，总额/价格不能超过最大可卖数量，超过时数量等于最大可卖数量，再用总额=价格*数量
    checkSellQuantityOnInputPrice (params) {
      let maxQuantity = commonFilter.fillDecimal(this.sellerAsset.AvailableAmount, this.pair.sellerPrecision)
      if (parseFloat(params.quantity) >= parseFloat(commonFilter.fillDecimal(this.sellerAsset.AvailableAmount, this.pair.sellerPrecision))) {
        params.quantity = maxQuantity
        params.price = this.calcPrice(params.total, params.quantity)
      }
    },
    bindEvent () {
      CheckCurrencyOnInput({}, this.$refs.buyPrice, 'price', () => this.pair.buyerPrecision, (newVal, lastValue, event) => {
        this.buyParams.price = newVal
        // this.calcWhich(newVal, lastValue, event, this.buyParams, 'price')
        this.calcWhich(newVal, lastValue, event, this.buyParams, 'quantity')
      })
      CheckCurrencyOnInput(this.buyParams, this.$refs.buyQuantity, 'quantity', () => this.pair.sellerPrecision, (newVal, lastValue, event) => {
        this.buyParams.quantity = newVal
        this.calcWhich(newVal, lastValue, event, this.buyParams, 'quantity')
      })
      CheckCurrencyOnInput(this.buyParams, this.$refs.marketBuyQuantity, 'quantity', () => this.pair.sellerPrecision, (newVal) => {
        this.buyParams.quantity = newVal
      })
      CheckCurrencyOnInput(this.buyParams, this.$refs.buyTotal, 'total', () => this.pair.buyerPrecision, (newVal, lastValue, event) => {
        this.buyParams.total = newVal
        this.calcWhich(newVal, lastValue, event, this.buyParams, 'total')
      })
      CheckCurrencyOnInput(this.sellParams, this.$refs.sellPrice, 'price', () => this.pair.buyerPrecision, (newVal, lastValue, event) => {
        this.sellParams.price = event.target.value = newVal
        // this.calcWhich(newVal, lastValue, event, this.sellParams, 'price')
        this.calcWhich(newVal, lastValue, event, this.sellParams, 'quantity')
      })
      CheckCurrencyOnInput(this.sellParams, this.$refs.sellQuantity, 'quantity', () => this.pair.sellerPrecision, (newVal, lastValue, event) => {
        this.sellParams.quantity = newVal
        this.calcWhich(newVal, lastValue, event, this.sellParams, 'quantity')
      })
      CheckCurrencyOnInput(this.sellParams, this.$refs.marketSellQuantity, 'quantity', () => this.pair.sellerPrecision, (newVal, lastValue, event) => {
        this.sellParams.quantity = newVal
        this.calcWhich(newVal, lastValue, event, this.sellParams, 'quantity')
      })
      CheckCurrencyOnInput(this.sellParams, this.$refs.sellTotal, 'total', () => this.pair.buyerPrecision, (newVal, lastValue, event) => {
        this.sellParams.total = newVal
        this.calcWhich(newVal, lastValue, event, this.sellParams, 'total')
      })
    },
    getBuyerAsset () {
      this.assetsList.forEach((asset) => {
        if (asset.ID === this.pair.BuyerCoinID) this.buyerAsset = asset
        if (asset.ID === this.pair.SellerCoinID) this.sellerAsset = asset
      })
    },
    getTradeStrategy () {
      // 只有登录才能获取交易策略，因为有些用户的手续费不一样
      this.$http.post('Trade/GetTradeGroupStrategy', {}, {
        isDisposeCode: false
      }).then((res) => {
        this.tradeStrategy = res.Data || []
        // 给数组添加key访问
        Utils.definePropertyForArray(this.tradeStrategy, 'TradingConfigID')
      })
    },
    // 获取规则
    getKYCRule () {
      return this.$http.get('Setting/GetKYCRule', {
        kYCConstraint: 2
      }, {
        isQueryString: true,
        isDisposeCode: false
      })
    },
    // 获取用户信息
    getCustomer () {
      return this.$http.post('Security/GetCustomer', {
      }, {
        isDisposeCode: false
      })
    },
    init () {
      // 切换交易对要清空
      this.buyParamsTemp = getDefaultParams()
      this.sellParamsTemp = getDefaultParams()
      this.toggleOrderType(1)
      this.isFirstGetBestPrices = true
    }
  },
  created () {
    EventBus.$on('switchPair', (pair) => {
      this.pair = pair
      this.init()
      this.isGotPair = true
      if (this.isGotPair && this.isGotAssetsList) this.getBuyerAsset()
    })

    EventBus.$on('updateAssets', (assetsList) => {
      this.assetsList = assetsList
      this.isGotAssetsList = true
      if (this.isGotPair && this.isGotAssetsList) this.getBuyerAsset()
    })

    EventBus.$on('fillInPrice', (info) => {
      // 点击卖的挂单，填入买入框，点击买的挂单，填入卖出框
      // 从别处来的价格，也要动态计算total
      if (this.userInfo.userName) {
        // 市价下不能在盘口点入价格
        if (this.orderType !== 0) {
          this.fillIn('price', commonFilter.fillDecimal(info.price, this.pair.buyerPrecision), this.buyParams)
          this.fillIn('price', commonFilter.fillDecimal(info.price, this.pair.buyerPrecision), this.sellParams)
        }
      }
    })

    EventBus.$on('fillInQuantity', (info) => {
      if (this.userInfo.userName) {
        if (info.side === 1) {
          this.fillIn('quantity', commonFilter.fillDecimal(info.quantity, this.pair.sellerPrecision), this.buyParams)
        } else {
          this.fillIn('quantity', commonFilter.fillDecimal(info.quantity, this.pair.sellerPrecision), this.sellParams)
        }
      }
    })

    EventBus.$on('updateLatestPrice', (info) => {
      info.price = (new Decimal(info.price || 0)).toFixed()
      this.latestPrice = info
    })

    // 每切换一次，只显示一次
    EventBus.$on('updateOrderBookBestPrices', (orderBookBestPrices = {}) => {
      this.orderBookBestPrices = orderBookBestPrices
      if (this.isFirstGetBestPrices) {
        // 卖一价填入买框，买一价填入卖框
        this.orderBookBestPrices[1] && (this.sellParams.price = commonFilter.fillDecimal(
          parseFloat(this.orderBookBestPrices[1].Price) ? this.orderBookBestPrices[1].Price : '',
          this.pair.buyerPrecision
        ))
        this.orderBookBestPrices[0] && (this.buyParams.price = commonFilter.fillDecimal(
          parseFloat(this.orderBookBestPrices[0].Price) ? this.orderBookBestPrices[0].Price : '',
          this.pair.buyerPrecision
        ))
        this.isFirstGetBestPrices = false
      }
    })
  },
  mounted () {
    this.bindEvent()

    if (this.userInfo.userName) {
      this.getTradeStrategy()

      this.getKYCRule().then((res) => {
        this.KYCRule = res.Data || {}

        // 需要认证才去请求用户认证信息
        this.KYCRule.IsEnaled && this.getCustomer().then((res) => {
          this.customer = res || {}
        })
      })
    }
  }
}
</script>

<style lang="less">
@import "./../../../mixins.less";
@white: #b5b8c0;
@labelWidth: 60px;
@tradeBoxPadding: 12px;
@coinDescWidth: 38px;
@coinSetWidth: 26px;
@tradeWidth: 320px - (@tradeBoxPadding * 2);
@tradeHeight: 256px;

.tradingPage {

  .tradeWrap {
    .mix-clearfix;
    position: relative;
    clear: both;
    width: 640px;
    color: @tradingFontColor;
    border-top: @tradingBorder;
    border-bottom: @tradingBorder;

    .tabTitle {
      .mix-clearfix;
      height: 29px;
      line-height: 29px;
      background-color: @tradingHeadBgColor;
      border-bottom: 1px solid #000;

      span {
        float: left;
        padding: 0 14px;
        text-align: center;
        cursor: pointer;
      }
      span.active {
        background-color: @tradingModuleBgColor;
      }
    }
    .tradeBox {
      float: left;
      padding: 0 @tradeBoxPadding;
      width: @tradeWidth;
      height: @tradeHeight;
      background-color: @tradingModuleBgColor;

      &.buy {
        width: @tradeWidth - 1px;
        border-right: 1px solid #39405a;
      }

      .head {
        margin-top: 16px;
        margin-bottom: 20px;
        line-height: 16px;

        .desc {
          font-size: 14px;
          color: #ccc;
        }
        .available {
          float: right;

          em {
            color: #ccc;
          }
        }
      }
    }
    @inputHeight: 30px;
    .inputBox {
      .mix-clearfix;
      margin-top: 14px;
      height: @inputHeight;
      line-height: @inputHeight;

      &.error {

        .input, .desc {background-color: rgba(148, 47, 47, 0.16);}
      }
      .label {
        float: left;
        width: @labelWidth;
      }
      .input {
        float: left;
        width: 170px;
        height: @inputHeight;
        text-indent: 6px;
        color: #ccc;
        outline: none;
        background-color: #2A3441;
      }
      input::-webkit-input-placeholder { /* WebKit browsers */
        color: #51637B;
      }
      input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
        color: #51637B;
      }
      input::-moz-placeholder { /* Mozilla Firefox 19+ */
        color: #51637B;
      }
      input:-ms-input-placeholder { /* Internet Explorer 10+ */
        color: #51637B;
      }
      .desc {
        float: left;
        overflow: hidden;
        width: @coinDescWidth;
        background-color: #2A3441;
      }
      .set {
        float: left;
        width: @coinSetWidth;
        height: 100%;
        line-height: 1;
        border: 1px solid #000;
        box-sizing: border-box;
      }
      .up, .down {
        display: block;
        width: 100%;
        height: 13px;
        line-height: 13px;
        text-align: center;
        font-size: 14px;
        color: #ccc;
        // background: url(./../images/up-price.png) no-repeat;
        background-color: #191F2B;
        cursor: pointer;
        user-select: none;
      }
      .up {
        height: 14px;
        line-height: 10px;
        border-bottom: 1px solid #000;
      }
      .down {
        line-height: 12px;
        font-size: 20px;
      }
    }
    .inputBox.disabled {
      position: relative;
      cursor: not-allowed;

      &:after {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
      }
    }
    .quantityRates {
      .mix-clearfix;
      display: flex;
      justify-content: space-between;
      margin-top: 10px;
      margin-left: 50px;

      .item {
        width: 54px;
        height: 28px;
        line-height: 28px;
        text-align: center;
        color: #80919C;
        border: 1px dashed #80919C;
        cursor: pointer;
        user-select: none;

        &:last-of-type {
          margin-right: 0;
        }

        &.active {
          color: #58C3E5;
          border-color: #58C3E5;
        }
      }
    }
    .total {
      margin-top: 10px;

      em {
        color: #fff;
      }
    }
    .btn {
      display: block;
      margin-top: 26px;
      width: 100%;
      height: 40px;
      line-height: 40px;
      text-align: center;
      font-weight: bold;
      font-size: 14px;
      color: #fff;
      border-radius: 5px;
      cursor: pointer;

      &.buy {
        background-color: #54A84E;
      }
      &.sell {
        background-color: #b23030;
      }
      &.disable {
        background-color: #bdbfbc;
      }

      span {
        display: inline-block;
        vertical-align: top;
        line-height: 1;
      }
    }
    .inputBox.price {
    }
    .inputBox.amount {

      input {
        width: 196px;
      }
    }
  }
}
.tradePasswordBox {
  margin: 16px 20px;
  width: 300px;

  .tip {
    font-size: 16px;
    color: #fff;
  }
  .error {
    margin-bottom: 10px;
    font-size: 12px;
    color: @downColor;
  }
  input {
    display: block;
    margin: 16px auto 10px;
    text-indent: 10px;
    width: 100%;
    height: 40px;
    line-height: 40px;
    color: #ccc;
    border: solid 0 #d5d5d5;
    border-radius: 4px;
    background-color: #2A3440;
  }
}

@media (max-width: @tradingPageMinWidth) {
  .tradingPage {
    @wrapWidth: @tradingCol2MinWidth;
    @buyBox: @wrapWidth / 2 - @tradeBoxPadding * 2 - 1;
    @sellBox: @wrapWidth / 2 - @tradeBoxPadding * 2;

    .tradeWrap {
      width: @wrapWidth;

      .tradeBox.buy {
        width: @buyBox;
      }
      .tradeBox.sell {
        width: @sellBox;
      }
      .inputBox .input {
        width: @buyBox - @labelWidth - @coinDescWidth - @coinSetWidth;
      }
      .inputBox.amount .input {
        width: @buyBox - @labelWidth - @coinDescWidth;
      }
      .quantityRates .item {
        width: (@buyBox - @labelWidth) / 4 - 8px;
      }
    }
  }
}
@media (max-height: @tradingPageMinHeight) {
.tradingPage {

  @inputHeight: 22px;

  .tradeWrap {

    .tabTitle {
      .mix-hl(23px);
    }
    .tradeBox {
      height: @tradeHeight - 96px;

      .head {
        margin-top: 7px;
        margin-bottom: 9px;
      }
      .head .desc {
        font-size: 12px;
      }
      .inputBox {
        margin-top: 9px;
        height: @inputHeight;
        line-height: @inputHeight;

        input {
          height: @inputHeight;
        }
        .up {
          height: 10px;
          line-height: 9px;
          font-size: 12px;
        }
        .down {
          height: 9px;
          line-height: 5px;
          font-size: 16px;
        }
      }
      .quantityRates {
        margin-top: 6px;

        span {
          .mix-hl(16px);
        }
      }
      .btn {
        .mix-hl(26px);

        margin-top: 12px;
        font-size: 12px;
      }
    }
    .total {
      margin-top: 5px;
    }
  }
}
}
</style>
